<template>
  <div class="login">
    <el-form :model="loginForm" status-icon :rules="loginRules" ref="loginRef" label-width="100px" class="login-form">
      <el-form-item prop="email" label="邮箱">
        <el-input v-model="loginForm.email"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="loginForm.password" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="验证码" prop="picVerification">
        <div class="pic-verification">
          <el-input type="password" v-model="loginForm.picVerification" autocomplete="off" @keyup.enter='clickLogin()'></el-input>
          <el-image class="pic-verification_image" :src="picUrl" fit="cover" @click="getPics()"></el-image>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="clickLogin()" style="width: 100%" :loading='loginForm.loading'>登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script lang="ts">
import { computed, defineComponent, getCurrentInstance, onMounted, reactive, ref } from 'vue'
import { validateEmail } from '@/utils/validate'
import { useRouter } from 'vue-router';
import { getPic, login, checkPic } from '@/http/api';
import { changeData } from '@/utils/dataStreamConversion';
import { useStore } from 'vuex';
class LoginForm {
  'email': string;
  'password': string;
  'picVerification': string;
  'loading': boolean
}
export default defineComponent({
  setup() {
    const routers = useRouter()
    const instance = getCurrentInstance()
    const store = useStore()
    console.log(instance?.appContext.config.globalProperties.$moment(new Date()).format('YYYY-MM-DD HH:mm:ss'));
    const loginForm = reactive<LoginForm>({
      email: '',
      password: '',
      picVerification: '',
      loading: false
    })
    const picUrl = ref<string>('')
    const loginRef = ref()
    let picVerificationKey = new Date().getTime()
    // 表单规则
    const loginRules = computed(() => {
      const checkEmail = (rule: any, value: string, callback: any) => {
        if (!value) {
          return callback(new Error('邮箱不能为空'));
        }
        if(validateEmail(value)) {
          return callback()
        }
        return callback(new Error('请输入正确的邮箱格式'));
      }
      return {
        'email': [{ required: true, validator: checkEmail, trigger: 'blur'}],
        'password': [{ required: true, message: '密码不能为空',trigger: 'blur'}],
        'picVerification': [{ required: true, message: '验证码不能为空',trigger: 'blur'},]
      }
    })
    // 获取图形验证码
    function getPics() {
      picVerificationKey = new Date().getTime()
      getPic({key: picVerificationKey}).then((res: any) => {
        picUrl.value = changeData(res, 'image/png')
      })
    }
    // 检查验证码
    function checkPics(token: string) {
      checkPic({key: picVerificationKey, code: loginForm.picVerification}).then(() => {
        store.commit('SET_TOKEN', token)
        loginForm.loading = false;
        routers.replace({path: '/'})
        // 重置表单
        loginRef.value.resetFields()
      }).catch(() => {
        loginForm.loading = false;
      })
    }
    // 点击登录
    function clickLogin() {
      loginRef.value.validate(async (valid: any) => {
        if (valid) {
          loginForm.loading = true
          await login({email: loginForm.email, pwd: loginForm.password, deviceId: '1', deviceName: 'pc端'}).then((res: any) => {
            checkPics(res.token)
          }).catch(() => {
            loginForm.loading = false;
            loginForm.picVerification = ''
            getPics()
          })
        } else {
          return false;
        }
      });
    }
    onMounted(() => {
      getPics()
    })
    return {
      loginForm,
      loginRules,
      loginRef,
      picUrl,
      clickLogin,
      getPics
    }
  }
})
</script>
<style lang="scss" scoped>
.login {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
.login-form {
  width: 400px;
}
.pic-verification {
  display: flex;
}
.pic-verification_image {
  width: 150px;
  padding-left: 10px;
  cursor: pointer;
}
</style>